//
//  AddressViewController.m
//  AntsExpress
//
//  Created by slccper on 16/1/8.
//  Copyright © 2016年 slccper. All rights reserved.
//

#import "AddressViewController.h"
#import <MapKit/MapKit.h>
#import "cImageView.h"
#import "clsFileFun.h"
#import "UIView-ViewFrameGeometry.h"
#import "WGS84TOGCJ02.h"
#import <MAMapKit/MAMapKit.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import <BaiduMapAPI_Map/BMKAnnotation.h>
#import "TPKeyboardAvoidingScrollView.h"
#define Default_Zoom_Level 16
#define MYBUNDLE_NAME @ "mapapi.bundle"
#define MYBUNDLE_PATH [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: MYBUNDLE_NAME]
#define MYBUNDLE [NSBundle bundleWithPath: MYBUNDLE_PATH]
@interface AddressViewController ()<cImageViewDelegate,BMKMapViewDelegate,BMKLocationServiceDelegate,UIGestureRecognizerDelegate,UIScrollViewDelegate>
{
    CLLocationManager *locationmanager;
    NSMutableArray *locationList;
    BMKLocationService* _locService;
    BMKAnnotationView* _annotation;
}
@property (weak, nonatomic) IBOutlet UILabel *address;
@property (weak, nonatomic) IBOutlet UILabel *date;
@property (weak, nonatomic) IBOutlet UITextView *mark;
@property (weak, nonatomic) IBOutlet BMKMapView *mapView;
@property (nonatomic, assign) double latitude;
@property (nonatomic, assign) double longitude;
@property (nonatomic, assign) BOOL IsEdit;
@property (nonatomic, assign) BOOL IsEmpty;
@property (weak, nonatomic) IBOutlet cImageView *Photo;
@property (weak, nonatomic) IBOutlet TPKeyboardAvoidingScrollView *ScrollView;

@end

@implementation AddressViewController
@synthesize latitude,longitude,IsEdit,IsEmpty;
- (void)viewDidLoad {
    [super viewDidLoad];
    if (_IOS8) {
        //是否具有定位权限
        BOOL enable=[CLLocationManager locationServicesEnabled];
        int status=[CLLocationManager authorizationStatus];
        if(!enable || status<3){
            //请求权限
            locationmanager = [[CLLocationManager alloc] init];
            [locationmanager requestWhenInUseAuthorization];
            [locationmanager startUpdatingLocation];
        }
    }
    self.title=[self.dic objectForKey:@"Name"];
    [self.address setText:[NSString stringWithFormat:@"%@%@",@"地址：",[self.dic objectForKey:@"Adress"]]];
    NSRange range;
    range.length=5;
    range.location=11;
    NSString *StartBusinessTime = [[self.dic objectForKey:@"StartBusinessTime"] substringWithRange:range];
    NSString *EndBusinessTime = [[self.dic objectForKey:@"EndBusinessTime"] substringWithRange:range];
    self.date.text=[NSString stringWithFormat:@"%@%@至%@",@"營業時間：",StartBusinessTime,EndBusinessTime];
    self.mark.text =[NSString stringWithFormat:@"%@%@",@"備註：",[self.dic objectForKey:@"MARK"]];
    NSString *x = [NSString stringWithFormat:@"%.6f",[[self.dic objectForKey:@"x"]doubleValue]];
    
    self.latitude =[x doubleValue];
    NSString *y = [NSString stringWithFormat:@"%.6f",[[self.dic objectForKey:@"y"]doubleValue]];
    self.longitude =[y doubleValue];
    self.address.numberOfLines=0;
    self.mark.scrollEnabled=NO;
    self.mark.frame = CGRectMake(15, 69, ScreenWidth-30, 100);
    self.mark.textColor = [UIColor whiteColor];
    
    _locService = [[BMKLocationService alloc]init];
    _mapView.centerCoordinate=CLLocationCoordinate2DMake(self.latitude, self.longitude);
    _mapView.zoomLevel=16;
    [_locService startUserLocationService];
    _mapView.showsUserLocation = NO;//先关闭显示的定位图层
    _mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
    _mapView.showsUserLocation = YES;//显示定位图层
    _mapView.delegate=self;
    _mapView.gesturesEnabled=YES;
    
    BMKPointAnnotation *annot = [[BMKPointAnnotation alloc]init];
    annot.coordinate = CLLocationCoordinate2DMake(self.latitude, self.longitude);
    annot.title=@"所在位置";
    [_mapView addAnnotation:annot];
    self.ScrollView.isBaidu=YES;
//    [self addCustomGestures];//添加自定义的手势
    
    
//    [self.mapview setMapType:MKMapTypeStandard];
//    self.mapview.delegate=self;
//    self.mapview.showsUserLocation=YES;
//    [self LoadData];
//    [self goToCompany];
    if ([self.dic objectForKey:@"ImgUrl"]) {
        NSArray *array = [[self.dic objectForKey:@"ImgUrl"] componentsSeparatedByString:@"/"];
        NSString *name = [array lastObject];
        NSString *url = [NSString stringWithFormat:@"%@",[array firstObject]];
        for (int i =1;i<array.count-1;i++) {
            url = [NSString stringWithFormat:@"%@/%@",url,array[i]];
        }
        self.Photo.activityView.color = [UIColor blackColor];
        self.Photo.serverDirectory = url;
        self.Photo.saveName = name;
        self.Photo.noNetImage = [UIImage imageNamed:@""];
        self.Photo.errorImage = self.Photo.noNetImage;
        self.Photo.noImage = self.Photo.noNetImage;
        self.Photo.contentMode=UIViewContentModeScaleAspectFit;
        self.Photo.delegate=self;
        [self.Photo loadImage];
    }
//    CLLocationCoordinate2D centerCoord= {latitude,longitude};
//    [self.mapview setCenterCoordinate:centerCoord zoomLevel:Default_Zoom_Level animated:NO];
    // Do any additional setup after loading the view from its nib.
}

-(void)viewWillAppear:(BOOL)animated {
    [_mapView viewWillAppear];
    _mapView.delegate = self;
    _locService.delegate = self;// 此处记得不用的时候需要置nil，否则影响内存的释放
}

-(void)viewWillDisappear:(BOOL)animated {
    [_mapView viewWillDisappear];
    _mapView.delegate = nil;
    _locService.delegate = nil;// 不用时，置nil
}
-(void)loadImageSuccess2:(cImageView *)imageView
{
    CGRect rect = self.Photo.frame;
    float height = ScreenWidth/imageView.image.size.width*imageView.image.size.height;
    rect.size.height=height;
    [self.Photo setFrame:CGRectMake(0, self.Photo.origin.y, ScreenWidth, height)];
    CGRect bound = [UIScreen mainScreen].bounds;
    [self.ScrollView setFrame:bound];
    if (bound.size.height>=736) {
        self.ScrollView.contentSize = CGSizeMake(ScreenWidth,self.Photo.bottom+171);
    }else if(bound.size.height>=666){
        self.ScrollView.contentSize = CGSizeMake(ScreenWidth,self.Photo.bottom+101);
    }else{
        self.ScrollView.contentSize = CGSizeMake(ScreenWidth,self.Photo.bottom);
    }
    if (bound.size.height==480) {
        bound.size.height+=84;
         [self.ScrollView setFrame:bound];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return NO;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return [gestureRecognizer isKindOfClass:UITapGestureRecognizer.class];
}
/*
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        MKUserLocation *userlocation=annotation;
        userlocation.title=@"當前位置";
        return nil;
    }
    
    if ([annotation isKindOfClass:[clsLocationData class]]) {
        static NSString* LocationIdentifier = @"LocationIdentifier";
        MKAnnotationView* locationview =
        (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:LocationIdentifier];
        if (!locationview)
        {
            locationview = [[MKPinAnnotationView alloc] initWithAnnotation:annotation
                                                           reuseIdentifier:LocationIdentifier];

//            locationview = [[MKAnnotationView alloc] initWithAnnotation:annotation
//             reuseIdentifier:LocationIdentifier];
//             locationview.canShowCallout = YES;
//             locationview.opaque = NO;
//            
//             UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
//             UIImage *icon=[UIImage imageNamed:@"g_calloutinfo.png"];
//             [button setImage:icon forState:UIControlStateNormal];
//             [button setImage:icon forState:UIControlStateHighlighted];
//             locationview.rightCalloutAccessoryView = button;
//             button=nil;
//             icon=nil;
            
        }
        else
        {
            locationview.annotation = annotation;
        }
        if (IsEdit==YES) {
            locationview.draggable = YES;
        }
        
        
//         clsLocationData *locationdata=annotation;
//         UIImage *flagImage;
//         flagImage = [UIImage imageNamed:@"g_other.png"];
//         flagImage=[self imageByScalingToSize:CGSizeMake(38, 40) image:flagImage];
//         locationview.image =[self getResizedImage:flagImage];
//         flagImage=nil;
//         
//         if (locationdata.image!=nil) {
//         UIImageView *iconView = [[UIImageView alloc] initWithImage:locationdata.image];
//         locationview.leftCalloutAccessoryView = iconView;
//         }
//         locationdata=nil;
        
        
        return locationview;
    }
    
    return nil;
}

-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control{
    if ([view.annotation isKindOfClass:[clsLocationData class]]) {

    }
}



- (void)mapViewDidFailLoadingMap:(MKMapView *)mapView withError:(NSError *)error{
    //UIAlertView* alert=[[UIAlertView alloc]initWithTitle:@"錯誤" message:@"載入地圖數據失敗!" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil];
    //[alert show];
}

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)annotationView didChangeDragState:(MKAnnotationViewDragState)newState fromOldState:(MKAnnotationViewDragState)oldState {
    
    if (newState == MKAnnotationViewDragStateEnding) {
        IsEmpty=NO;
    }
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    //完成显示当前位置
    if (userLocation.coordinate.latitude==0 || userLocation.coordinate.longitude==0) {
        return;
    }
    if (IsEmpty) {
        [self goToMyLocation];
        
        clsLocationData * newLocation=[locationList objectAtIndex:0];
        [newLocation setCoordinate:userLocation.coordinate];
        
        IsEmpty=NO;
    }
}
-(void)goToMyLocation{
    CLLocationCoordinate2D centerCoord = self.mapview.userLocation.coordinate;
    if ([WGS84TOGCJ02 isLocationOutOfChina:centerCoord]) {
        
    }
    [self.mapview setCenterCoordinate:centerCoord zoomLevel:Default_Zoom_Level animated:NO];
}
-(void)LoadData{
//    isLoadingData=YES;
    locationList = [[NSMutableArray alloc] initWithCapacity:0];
    [self CreateCompanyData];
    //[BtnShowCompanyLoc setTitle:@"當前公司" forState:UIControlStateNormal];
//    isLoadingData=NO;
//    
//    isSetingData=YES;
    //if([omapview getZoomLevel]>=Zoom_Min_Level){
    for (id <MKAnnotation> annotation in [self.mapview annotations]) {
        if (![annotation isKindOfClass:[MKUserLocation class]])
            [self.mapview removeAnnotation:annotation];
    }
    
    [self.mapview addAnnotations:locationList];
    //isAddLocation=YES;
    //}
//    isSetingData=NO;
}
-(void)CreateCompanyData{
    CLLocationCoordinate2D newCoord={self.latitude,self.longitude};
   
    clsLocationData * newLocation= [[clsLocationData alloc] init];
    newLocation.coordinate=newCoord;
    if (IsEdit==YES) {
        newLocation.name=@"取貨點所在位置";
    }
    
    [locationList addObject:newLocation];
    newLocation=nil;
}
-(void)goToCompany{
    CLLocationCoordinate2D centerCoord= {latitude,longitude};
    [self.mapview setCenterCoordinate:centerCoord zoomLevel:Default_Zoom_Level animated:NO];
}
-(void)getAntsDataSuccess:(NSInteger)type :(NSMutableDictionary *)pDictionary
{
    NSDictionary *dic = [pDictionary objectForKey:@"data"];
    NSArray *data = [dic objectForKey:@"data"];
}
*/
- (void)dealloc
{
    
}
#pragma mark - BMKMapViewDelegate

- (void)mapViewDidFinishLoading:(BMKMapView *)mapView {
    //    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"BMKMapView控件初始化完成" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles: nil];
    //    [alert show];
    //    alert = nil;
}

- (void)mapView:(BMKMapView *)mapView onClickedMapBlank:(CLLocationCoordinate2D)coordinate {
    NSLog(@"map view: click blank");
}

- (void)mapview:(BMKMapView *)mapView onDoubleClick:(CLLocationCoordinate2D)coordinate {
    NSLog(@"map view: double click");
}

#pragma mark - 添加自定义的手势（若不自定义手势，不需要下面的代码）

- (void)addCustomGestures {
    /*
     *注意：
     *添加自定义手势时，必须设置UIGestureRecognizer的属性cancelsTouchesInView 和 delaysTouchesEnded 为NO,
     *否则影响地图内部的手势处理
     */
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
    doubleTap.delegate = self;
    doubleTap.numberOfTapsRequired = 2;
    doubleTap.cancelsTouchesInView = NO;
    doubleTap.delaysTouchesEnded = NO;
    
    [self.view addGestureRecognizer:doubleTap];
    
    /*
     *注意：
     *添加自定义手势时，必须设置UIGestureRecognizer的属性cancelsTouchesInView 和 delaysTouchesEnded 为NO,
     *否则影响地图内部的手势处理
     */
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    singleTap.delegate = self;
    singleTap.cancelsTouchesInView = NO;
    singleTap.delaysTouchesEnded = NO;
    [singleTap requireGestureRecognizerToFail:doubleTap];
    [self.view addGestureRecognizer:singleTap];
}

- (void)handleSingleTap:(UITapGestureRecognizer *)theSingleTap {
    /*
     *do something
     */
    NSLog(@"my handleSingleTap");
}

- (void)handleDoubleTap:(UITapGestureRecognizer *)theDoubleTap {
    /*
     *do something
     */
    NSLog(@"my handleDoubleTap");
}

/**
 *用户方向更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    [_mapView updateLocationData:userLocation];
    NSLog(@"heading is %@",userLocation.heading);
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    //    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    [_mapView updateLocationData:userLocation];
}

/**
 *在地图View停止定位后，会调用此函数
 *@param mapView 地图View
 */
- (void)didStopLocatingUser
{
    NSLog(@"stop locate");
}

/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"location error");
}
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation
{
    if (_annotation == nil) {
        _annotation = [[BMKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"annot"];
        _annotation.image = [UIImage imageNamed:@"pin_red.png"];
        //        _annotation.centerOffset = CGPointMake(0, -(view.frame.size.height * 0.5));
        _annotation.canShowCallout = TRUE;
    }
    return _annotation;
}
- (NSString*)getMyBundlePath1:(NSString *)filename
{
    
    NSBundle * libBundle = MYBUNDLE ;
    if ( libBundle && filename ){
        NSString * s=[[libBundle resourcePath ] stringByAppendingPathComponent : filename];
        return s;
    }
    return nil ;
}

@end
